<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="queryForm" class="query-form">
        <el-form-item label="综合查询">
          <el-input v-model.trim="queryForm.keywords" style="width: 180px;" clearable placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item label="PID">
          <el-input v-model.trim="queryForm.pid" style="width: 180px;" clearable placeholder="请输入PID" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="queryForm.roles" multiple collapse-tags collapse-tags-tooltip placeholder="请选择角色"
            style="width: 180px;" clearable>
            <el-option v-for="item in roleList" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门">
          <el-tree-select v-model="queryForm.deptId" :data="deptList"
            :props="{ value: 'id', label: 'name', children: 'children' }" node-key="id" placeholder="请选择部门"
            check-strictly default-expand-all style="width: 180px;" clearable />
        </el-form-item>
        <el-form-item label="用户状态">
          <el-select v-model="queryForm.status" placeholder="请选择用户状态" style="width: 180px;" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="登录时间">
          <el-date-picker v-model="queryForm.loginTime" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="YYYY-MM-DD" style="width: 220px;" clearable />
        </el-form-item>
        <el-form-item label="登录IP">
          <el-input v-model.trim="queryForm.loginIp" style="width: 180px;" clearable placeholder="请输入登录IP" />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="queryForm.createTime" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="YYYY-MM-DD" style="width: 220px;" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" border stripe style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="pid" label="PID" width="80">
          <template #default="scope">
            <span>{{ scope.row.pid || "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" min-width="180" show-overflow-tooltip />
        <el-table-column prop="nickname" label="昵称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.email || "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.phone || "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="roles" label="角色" min-width="160" show-overflow-tooltip>
          <template #default="scope">
            {{ formatRoles(scope.row.roles) }}
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="部门" min-width="180" show-overflow-tooltip />
        <el-table-column prop="status" label="用户状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="loginTime" label="登录时间" width="180">
          <template #default="scope">
            {{ $formatTimestamp(scope.row.loginTime) || "--" }}
          </template>
        </el-table-column>
        <el-table-column prop="loginIp" label="登录IP" min-width="140" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.loginIp || "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ $formatTimestamp(scope.row.createTime) || "--" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="height: 18px;"></div>

      <el-pagination v-model:current-page="queryForm.pageNum" v-model:page-size="queryForm.pageSize"
        :page-sizes="[10, 50, 100, 500, 1000]" :total="total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" destroy-on-close>
      <el-form ref="formRef" :model="userForm" :rules="userRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model.trim="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model.trim="userForm.password" placeholder="请输入密码(可选)" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model.trim="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="userForm.roles" multiple placeholder="请选择角色" style="width: 100%;">
            <el-option v-for="item in roleList" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-tree-select v-model="userForm.deptId" :data="deptList"
            :props="{ value: 'id', label: 'name', children: 'children' }" node-key="id" placeholder="请选择部门"
            check-strictly default-expand-all style="width: 100%;" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model.trim="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="用户状态" prop="status">
          <el-select v-model="userForm.status" placeholder="请选择用户状态">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { apiUserList, apiUserAdd, apiUserUpdate, apiUserDelete } from '@/api/system/user'
import { apiRoleCacheList } from '@/api/system/role'
import { apiGetDeptTree } from '@/api/system/dept'
import md5 from 'js-md5'

// 查询表单
const queryForm = ref<Record<string, any>>({
  pageNum: 1,
  pageSize: 10
})

// 数据列表
const roleList = ref<any[]>([])
const deptList = ref<any[]>([])
const list = ref<any[]>([])
const total = ref(0)

// 角色列表
const initRoleList = async () => {
  const res = await apiRoleCacheList()
  roleList.value = res.data || []
}

// 部门列表
const initDeptList = async () => {
  const res = await apiGetDeptTree()
  deptList.value = res.data || []
}

// 获取列表
const fetchList = async () => {
  const res = await apiUserList(queryForm.value)
  list.value = res.data.records
  total.value = res.data.totalRow
}

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 用户表单
const initUserForm = ref<Record<string, any>>({
  status: 1
})
const userForm = ref<Record<string, any>>({ ...initUserForm.value })

// 表单验证规则
const userRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  roles: [{ required: true, message: '请选择角色', trigger: 'change' }],
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
}

// 表单引用
const formRef = ref()

// 查询
const handleQuery = () => {
  queryForm.value.pageNum = 1
  fetchList()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  isEdit.value = false
  // 重置表单
  Object.assign(userForm.value, initUserForm.value)
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑用户'
  isEdit.value = true
  // 填充表单数据
  Object.assign(userForm.value, row)
  if (userForm.value.roles) {
    userForm.value.roles = userForm.value.roles.split(',')
  }
  dialogVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除【${row.username}】吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await apiUserDelete({ ids: String(row.id) })
    if (res.code == 200) {
      ElMessage.success('删除成功')
      handleQuery()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.warning('请先选择要删除的数据')
    return
  }
  const ids = multipleSelection.value.map((item: any) => item.id).join(',')
  ElMessageBox.confirm(`确定要删除选中的数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await apiUserDelete({ ids: ids })
    if (res.code == 200) {
      ElMessage.success('删除成功')
      handleQuery()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  })
}

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (valid: any) => {
    if (valid) {
      let res: any;
      if (userForm.value.roles) {
        //将角色列表转换为逗号分隔的字符串
        userForm.value.roles = userForm.value.roles.join(',')
      }
      // 对密码进行MD5加密
      if (userForm.value.password) {
        userForm.value.password = md5.md5(userForm.value.password)
      }
      if (isEdit.value) {
        res = await apiUserUpdate(userForm.value)
      } else {
        res = await apiUserAdd(userForm.value)
      }
      if (res.code == 200) {
        ElMessage.success('保存成功')
        dialogVisible.value = false
        handleQuery()
      } else {
        ElMessage.error(res.message || '保存失败')
      }
    }
  })
}

// 分页相关
const handleSizeChange = (val: number) => {
  queryForm.value.pageSize = val
  queryForm.value.pageNum = 1
  fetchList()
}

const handleCurrentChange = (val: number) => {
  queryForm.value.pageNum = val
  fetchList()
}

// 多选
const multipleSelection = ref<[]>([])
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
}

// 格式化角色列表
const formatRoles = (roles: string) => {
  if (!roles) return '--'
  return roles.split(',').map(code =>
    roleList.value.find(role => role.code === code)?.name || code
  ).join(',')
}

// 初始化
onMounted(async () => {
  await initRoleList()
  await initDeptList()
  await fetchList()
})
</script>

<style scoped>
.app-container {
  padding: 0px;
}

.query-form {
  margin-bottom: 0px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}
</style>